package concurrent.tool;

import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;

import org.junit.Test;

public class FutureAndCallableTest {

	@Test
	public void test1() throws InterruptedException, ExecutionException {
		Callable<Integer> callable = new Callable<Integer>() {
			@Override
			public Integer call() throws Exception {
				Thread.sleep(5000);
				return new Random().nextInt();
			}
		};
		
		FutureTask<Integer> future = new FutureTask<>(callable);
		new Thread(future).start();
		Integer result = future.get();
		System.out.println(result);
	}
	
	@Test
	public void test2() throws InterruptedException, ExecutionException {
		ExecutorService service = Executors.newSingleThreadExecutor();
		Future<Integer> future = service.submit(new Callable<Integer>() {
			@Override
			public Integer call() throws Exception {
				Thread.sleep(5000);
				return new Random().nextInt();
			}
		});
		System.out.println(future.get());
	}
}
